package dto

import (
	"time"
	"wxpay/internal/model"
	"wxpay/pkg/util"

	"gorm.io/datatypes"
)

type ReceiverInProfitShare struct {
	// 分账接收方类型
	Type string
	// 分账接收方帐号
	Account string
	// 分账动账金额
	Amount int64
	// 分账/回退描述
	Description string
	// 分账接受方姓名
	ReceiverName string
}

type ProfitOrderDTO struct {
	// ID
	ID int64
	// 品牌id
	BrandID string
	// 商户订单编号
	OutTradeNo string
	// 商户分账单号
	OutOrderNo string
	// 二级商户商户号
	SubMchID string
	// 分账接受方
	Receivers []ReceiverInProfitShare
	// 是否完结分账
	Finish bool
	// 微信分账单号
	WxOrderID string
	// 服务商商户号
	MchID string
	// 服务商appid
	AppID string
	// 微信支付单号
	WxTransID string
	// 分账完结描述(仅分账完结有)
	Description string
}

func (p *ProfitOrderDTO) GetTotalShareAmount() (total int64) {
	for _, r := range p.Receivers {
		total += r.Amount
	}
	return
}

type MchAPIReceiver struct {
	// 分账接收方类型
	Type string `json:"type"`
	// 分账接收方帐号
	Account string `json:"receiver_account"`
	// 分账动账金额
	Amount uint `json:"amount"`
	// 分账/回退描述
	Description string `json:"description"`
	// 分账接受方姓名
	ReceiverName string `json:"receiver_name"`
}

// dto to model
func AdaptProfitShare(info *ProfitOrderDTO) (r model.Profitshare) {
	r = model.Profitshare{
		BrandID:           info.BrandID,
		MchID:             info.MchID,
		SubMchID:          info.SubMchID,
		AppID:             info.AppID,
		WxTransID:         info.WxTransID,
		WxOrderID:         util.AdaptNullString(info.WxOrderID),
		OutTradeNo:        info.OutTradeNo,
		OutOrderNo:        info.OutOrderNo,
		Receivers:         adaptReceivers(info.Receivers),
		FinishDescription: util.AdaptNullString(info.Description),
		CreateTime:        util.GetNow(),
		UpdateTime:        util.GetNow(),
	}
	return
}

func adaptReceivers(receivers []ReceiverInProfitShare) (r datatypes.JSON) {
	m := make(model.Receivers, len(receivers))
	for i, rcv := range receivers {
		m[i] = model.Receiver{
			Type:         rcv.Type,
			Account:      rcv.Account,
			Amount:       rcv.Amount,
			Description:  rcv.Description,
			ReceiverName: rcv.ReceiverName,
		}
	}
	r = m.ToJson()
	return
}

type UnSplitAmountDTO struct {
	// 订单剩余待分金额
	UnSplitAmount int64
}

func ConvertProfitShare(info *model.Profitshare) (r *ProfitOrderDTO) {
	r = &ProfitOrderDTO{
		ID:          info.ID,
		BrandID:     info.BrandID,
		OutTradeNo:  info.OutTradeNo,
		OutOrderNo:  info.OutOrderNo,
		SubMchID:    info.SubMchID,
		Receivers:   nil,
		Finish:      false,
		WxOrderID:   util.ConvertNullString(info.WxOrderID),
		MchID:       info.MchID,
		AppID:       info.AppID,
		WxTransID:   info.WxTransID,
		Description: util.ConvertNullString(info.FinishDescription),
	}
	return
}

type ProfitOrderNotify struct {
	// 分账完结金额(仅分账完结有)
	FinishAmount int64
	// 分账单状态
	Status string
	// 关单原因
	CloseReason string
}

type ProfitReturnNotify struct {
	// 回退结果
	Result string
	// 失败原因
	FailReason string
	// 完成时间
	FinishTime *time.Time
}
